//
//  NewFeatureViewController.swift
//  Weibo10
//
//  Created by 刘凡 on 15/10/17.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit
import SnapKit

/// 可重用标识符
private let WBNewFeatureViewCellID = "WBNewFeatureViewCellID"
/// 新特性数量
private let WBNewFeatureCount = 4

/// 新特性界面
class NewFeatureViewController: UICollectionViewController {
    
    // MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        
        layout.itemSize = UIScreen.mainScreen().bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .Horizontal
        
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        prepareCollectionView()
    }
    
    /// 隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    /// 准备 CollectionView
    private func prepareCollectionView() {
        collectionView?.backgroundColor = UIColor.whiteColor()
        // 注册可重用 Cell
        collectionView!.registerClass(NewFeatureViewCell.self, forCellWithReuseIdentifier: WBNewFeatureViewCellID)
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
}

// MARK: - 数据源方法 & 代理方法
extension NewFeatureViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return WBNewFeatureCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(WBNewFeatureViewCellID, forIndexPath: indexPath) as! NewFeatureViewCell
        
        cell.imageIndex = indexPath.item
        
        return cell
    }
    
    // 滚动视图停止滚动
    override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        
        let offset = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        if offset != WBNewFeatureCount - 1 {
            return
        }
        
        // 播放动画
        (collectionView?.visibleCells().last as? NewFeatureViewCell)?.showStartButton()
    }
}

// MARK: - 新特性 Cell
private class NewFeatureViewCell: UICollectionViewCell {
    
    /// 图像索引
    var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            
            startButton.hidden = true
        }
    }
    
    /// 点击启动按钮
    @objc private func clickStartButton() {
        print("开始体验")
        
        NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: nil)
       
    }
    
    /// 动画显示开始按钮
    private func showStartButton() {
        startButton.hidden = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.2,         // 动画时长
            delay: 0,
            usingSpringWithDamping: 0.8,        // 弹力系数
            initialSpringVelocity: 10,          // 初始速度
            options: [],                        // 动画选项
            animations: {
                
                self.startButton.transform = CGAffineTransformIdentity
                
        }) { (_)  in
            
            self.startButton.userInteractionEnabled = true
        }
    }
    
    // MARK: - 设置界面
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        // 添加控件
        addSubview(iconView)
        addSubview(startButton)
        
        // 设置圆角
        startButton.layer.cornerRadius = 5
        startButton.layer.masksToBounds = true
        
        // 自动布局
        iconView.frame = bounds
        startButton.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(snp_centerX)
            make.bottom.equalTo(snp_bottom).multipliedBy(0.7)
        }
        
        // 添加监听方法
        startButton.addTarget(self, action: #selector(NewFeatureViewCell.clickStartButton), forControlEvents: .TouchUpInside)
    }
    
    // MARK: - 懒加载控件
    /// 新特性图像
    private lazy var iconView = UIImageView()
    /// 开始体验按钮
    private lazy var startButton: UIButton = UIButton(title: "开始体验",color: UIColor.whiteColor(),backImageName: "new_feature_finish_button")
    
}



